package Thread;

/*
 * Author: JacksonCoder
 * FileName: ForkJoinPoolExample
 * Version: 1.0.0
 * Date: 2025/1/23
 */

import java.util.concurrent.*;

public class ForkJoinPoolExample {

    public static void main(String[] args) {

        // 创建ForkJoinPool
        ForkJoinPool pool = new ForkJoinPool();
        // 提交任务
        FibonacciTask task = new FibonacciTask(10);
        int result = pool.invoke(task);

        System.out.println("Fibonacci(10) = " + result);

        // 关闭线程池
        pool.shutdown();

    }

    static class FibonacciTask extends RecursiveTask<Integer> {
        private final int n;

        public FibonacciTask(int n) {
            this.n = n;
        }

        @Override
        protected Integer compute() {
            if (n <= 1) {
                return n;
            } else {
                // 分解任务
                FibonacciTask task1 = new FibonacciTask(n - 1);
                FibonacciTask task2 = new FibonacciTask(n - 2);

                task1.fork(); // 异步执行子任务
                int result2 = task2.compute(); // 同步执行子任务
                int result1 = task1.join(); // 获取子任务结果

                return result1 + result2;
            }
        }
    }
}
